﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Caliburn.Micro;
using JY.Wpf.Core.Enums;
using JY.Wpf.Core.Events;
using JY.Wpf.Core.ViewModelBases;
using JY.Wpf.Test.Views.CaliburnDemoViews;
using SD.IOC.Core.Mediators;

namespace JY.Wpf.Test.ViewModels.CaliburnDemoViewModels
{
    /// <summary>
    /// ResultViewModel
    /// </summary>
    public class ResultViewModel : ViewModelBase
    {
        #region # 变量

        #endregion

        #region # 构造器

        /// <summary>
        /// 构造器
        /// </summary>
        public ResultViewModel()
        {

        }

        #endregion

        #region # 属性

        #endregion

        #region # Command方法

        public IEnumerable<IResult> TestIResult()
        {
            List<IResult> results = new List<IResult>();
            var loader = new Loader("第一步");
            //var loader2 = new Loader2("第二步");
            var loader3 = new Loader("第三步");
            loader.Completed += First_Completed;
            loader3.Completed += Third_Completed;

            //results.Add(loader);
            //results.Add(loader2);
            //results.Add(loader3);
            //return results;
            yield return loader;

            var loader2 = new Loader2("第二步"+loader.Result);
            loader2.Completed += Second_Completed;
            yield return loader2;
            yield return loader3;
        }
        public async void TestIResult2()
        {
            List<IResult> results = new List<IResult>();
            var loader = new Loader("第一步");
            var loader2 = new Loader2("第二步");
            var loader3 = new Loader("第三步");
            loader.Completed += (s, e) =>
            {
                loader2._str = "第二步" + loader.Result;
            };
            loader3.Completed += Third_Completed;

            results.Add(loader);
            results.Add(loader2);
            results.Add(loader3);
            //Coroutine.BeginExecute(results.GetEnumerator());
            await Coroutine.ExecuteAsync(results.GetEnumerator());
            MessageBox.Show("手动执行IResult完成！");
        }

        private void First_Completed(object sender, ResultCompletionEventArgs e)
        {
        }
        private void Second_Completed(object sender, ResultCompletionEventArgs e)
        {
        }
        private void Third_Completed(object sender, ResultCompletionEventArgs e)
        {
        }


        #endregion

        #region # 方法

        #endregion

        #region # 获取页面 —— object GetView(object context = null)

        /// <summary>
        /// 获取页面
        /// </summary>
        /// <param name="context">页面</param>
        /// <returns></returns>
        public override object GetView(object context = null)
        {
            return ResolveMediator.Resolve<ResultView>();
        }

        #endregion
    }
    public class Loader : IResult<string>
    {
        private readonly string _str;
        public Loader(string str)
        {
            _str = str;
        }

        public async void Execute(CoroutineExecutionContext context)
        {
            try
            {
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(true, this._str));
                await Task.Run(() =>
                    {
                        Thread.Sleep(3000);
                        //throw new Exception("测试异常！");
                    });
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(false));
                Result = "【" + this._str + "返回结果：" + DateTime.Now + "】";
                this.Completed(this, new ResultCompletionEventArgs());
            }
            catch (Exception ex)
            {
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(false));
                //this.Completed(this, new ResultCompletionEventArgs());
                //Error赋值则直接取消后面的Result执行。WasCancelled设置为True强制取消后面的Result执行
                this.Completed(this, new ResultCompletionEventArgs()
                {
                    Error = ex
                });
                this.Completed(this, new ResultCompletionEventArgs()
                {
                    WasCancelled = true
                });
            }
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = (sender, args) =>
        {
        };

        public string Result { get; set; }
    }
    public class Loader2 : IResult
    {
        public string _str;
        public Loader2(string str)
        {
            _str = str;
        }

        public async void Execute(CoroutineExecutionContext context)
        {
            try
            {
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(true, this._str));
                await Task.Run(() =>
                {
                    Thread.Sleep(3000);
                });
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(false));
                this.Completed(this, new ResultCompletionEventArgs());
            }
            catch (Exception ex)
            {
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(false));
                this.Completed(this, new ResultCompletionEventArgs()
                {
                    Error = ex,
                    WasCancelled = true
                });
            }
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = (sender, args) =>
        {
        };
    }
}
